package com.mini.cn.goods.lottery;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.ReentrantLock;


/**
 * Created by fly on 17/3/29.
 */
public class PeopleLottery extends LotteryGo {

    List<Area> areas;
    private final ReentrantLock mainLock = new ReentrantLock();

    public PeopleLottery(List<Prize> prizes, int peopleNumber) {
        this.peopleNumber = peopleNumber;
        this.prizes = prizes;
        areas = new ArrayList<Area>();
    }

    public PeopleLottery(){
        areas=new ArrayList<Area>();
    }

    @Override
    public void creatLottoeyBox() {
        int pos = 0;
        areas.clear();
        for (int i = 0; i < prizes.size(); i++) {
            Prize prize = prizes.get(i);
            int poll = prize.poll;
            if (poll > 0) {
                Area area = new Area();
                area.prize = prize;
                area.start = pos;
                area.over = pos + poll;
                areas.add(area);
                pos += prize.poll;
            }
        }
    }

    @Override
    public Prize LotteryPrize() {
        mainLock.lock();
        try {
            System.out.println("剩余人数==" + peopleNumber);
            if (peopleNumber > 0) {
                creatLottoeyBox();
                int total = 0;
                for (int i = 0; i < prizes.size(); i++) {
                    Prize prize = prizes.get(i);
                    total += prize.poll;
                }
                System.out.println("剩余奖品数==" + total);
                if (total > 0) {
                    int speed = Math.max(total, peopleNumber);
                    int pos = ThreadLocalRandom.current().nextInt(speed);
                    System.out.println("Thread id=" + Thread.currentThread().getId() + "   抽奖随机数=" + pos);
                    peopleNumber -= 1;
                    for (int i = 0; i < areas.size(); i++) {
                        Area area = areas.get(i);
                        int start = area.start;
                        int over = area.over;
                        Prize key = area.prize;
                        if (pos >= start && pos < over) {
                            if (area.prize.poll > 0) {
                                area.prize.poll -= 1;
                                return key;
                            }
                        }
                    }
                }
            }
        } finally {
            mainLock.unlock();
        }

        return null;
    }

    @Override
    public void clearLotteryBuffer() {
        areas.clear();
        areas = null;
        prizes.clear();
        prizes = null;
        peopleNumber = 0;
    }
}
